import React, { useState, useEffect, useRef } from 'react';
import '../../style/main.css';
import '../../style/kuangjia.css';
import { useGlobalContext } from '../GlobalContext';

const MusicPlayer = ({ playingsong, isLyricVisible, onLyricVisibilityChange, setCurTim }) => {
  const [isFirstLoad, setIsFirstLoad] = useState(true);
  const { playerlistfresh, currentIndex, setCurrentIndex, playingDatalength, setPlayingDatalength } = useGlobalContext();
  const [songData, setSongData] = useState([]);
  const [currentSong, setCurrentSong] = useState({});
  const audioRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [volume, setVolume] = useState(1); // 默认音量

  useEffect(() => {
    if (songData.length > 0 && currentIndex >= 0 && currentIndex < songData.length) {
      setCurrentSong(songData[currentIndex]);
      playingsong(songData[currentIndex])
    }
  }, [currentIndex, songData]);

  useEffect(() => {
    const audio = audioRef.current;
    if (audio && currentSong?.playUrl) {
      audio.src = currentSong.playUrl;
      audio.load();
      audio.addEventListener('timeupdate', handleTimeUpdate);
      audio.addEventListener('ended', handleSongEnd);

      setDuration(audio.duration);
      if (!isFirstLoad) {
        audio.play();
        setIsPlaying(true);
      } else {
        setIsFirstLoad(false);
      }
    }
    return () => {
      if (audio) {
        audio.removeEventListener('timeupdate', handleTimeUpdate);
        audio.removeEventListener('ended', handleSongEnd);
      }
    };
  }, [currentSong]);

  const getPlayUrl = async (id) => {
    try {
      const response = await fetch(`http://localhost:3000/song/url?id=${id}`);
      const data = await response.json();
      return data.data[0]?.url || '';
    } catch (error) {
      console.error('Error fetching song URL:', error);
      return '';
    }
  };

  useEffect(() => {
    const fetchSongData = async () => {
      try {
        const response = await fetch('http://localhost:8088/playing/allsortBysongIndex');
        const data = await response.json();
        const songs = data.data;

        const songDetails = await Promise.all(
          songs.map(async (song) => {
            const playUrl = await getPlayUrl(song.musicId);
            return {
              musicId: song.musicId,
              musicName: song.musicName,
              artName: song.artName || '未知',
              album: song.album,
              coverUrl: song.coverUrl,
              lyricUrl: `http://localhost:3000/lyric?id=${song.musicId}`,
              dt: song.dt,
              playUrl,
              liked: song.liked,
            };
          })
        );

        setSongData(songDetails);
        setPlayingDatalength(songDetails.length)
        // 确保 currentIndex 合法
        if (songDetails.length > 0) {
          setCurrentIndex((prevIndex) => Math.min(prevIndex, songDetails.length - 1));

        }
      } catch (error) {
        console.error('Error fetching song data:', error);
      }
    };

    fetchSongData();
  }, [playerlistfresh]); // 依赖 playerlistfresh 触发数据刷新


  const togglePlayPause = () => {
    const audio = audioRef.current;
    if (isPlaying) {
      audio.pause();
    } else {
      audio.play();
    }
    setIsPlaying(!isPlaying);
  };

  const handleTimeUpdate = () => {
    const audio = audioRef.current;
    if (!isDragging) {
      setCurTim(audio.currentTime);
      setCurrentTime(audio.currentTime);
      setProgress((audio.currentTime / audio.duration) * 100);
    }
  };

  const handleProgressChange = (e) => {
    const audio = audioRef.current;
    const newTime = (e.target.value / 100) * audio.duration;
    setProgress(e.target.value);
    if (isDragging) {
      audio.currentTime = newTime;
    }
  };

  const handleMouseDown = () => {
    setIsDragging(true);
    const audio = audioRef.current;
    audio.pause();
  };

  const handleMouseUp = () => {
    setIsDragging(false);
    const audio = audioRef.current;
    audio.play();
  };

  const handleNextSong = () => {
    if (currentIndex < songData.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else {
      // 如果是最后一首歌，跳转到第一首
      setCurrentIndex(0);
    }
    playingsong(songData[currentIndex]);
  };

  const handlePreviousSong = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    } else {
      // 如果是第一首歌，跳转到最后一首
      setCurrentIndex(songData.length - 1);
    }
    playingsong(songData[currentIndex]);
  };

  const handleSongEnd = () => {
    handleNextSong();
  };

  const toggleLyricVisibility = () => {
    onLyricVisibilityChange(!isLyricVisible);
  };

  const handleVolumeChange = (e) => {
    const newVolume = e.target.value / 100;
    setVolume(newVolume);

    const audio = audioRef.current;
    if (audio) {
      audio.volume = newVolume; // 同步音量到 audio
    }
  };

  const formatDuration = (duration) => {
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  const formatDuration2 = (durationInMilliseconds) => {
    const durationInSeconds = Math.floor(durationInMilliseconds / 1000);
    const minutes = Math.floor(durationInSeconds / 60);
    const seconds = Math.floor(durationInSeconds % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  return (
    <div className="buttom">
      <audio ref={audioRef} id="audio-player" preload="auto" />
      <div className="start">
        <div className="music-small-img" onClick={toggleLyricVisibility}>
          <img id="playsongImg" src={currentSong.coverUrl} alt="music-logo" />
        </div>
        <div className="music-information">
          <ul>
            <li id="playsongname">{currentSong.musicName}</li>
            <li id="playsinger">{currentSong.artName}</li>
          </ul>
        </div>
      </div>

      <div className="center">
        <div className="mediaControl">
          <ul>
            <li>
              <i
                className="ri-skip-back-fill"
                onClick={handlePreviousSong}
              // style={{ color: currentIndex === 0 ? 'gray' : 'black' }}
              ></i>
            </li>
            <li>
              <i
                onClick={togglePlayPause}
                id="play_pause"
                className={isPlaying ? 'ri-pause-line' : 'ri-play-fill'}
              ></i>
            </li>
            <li>
              <i
                className="ri-skip-forward-fill"
                onClick={handleNextSong}
              // style={{ color: currentIndex === songData.length - 1 ? 'gray' : 'black' }}
              ></i>
            </li>
          </ul>
        </div>

        <div className="mediaprogress">
          <span id="currenttime">{formatDuration(currentTime)}</span>
          <input
            type="range"
            value={progress}
            onChange={handleProgressChange}
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
            className="progress-bar"
            style={{
              background: `linear-gradient(to right, #4CAF50 ${progress}%, #ddd ${progress}%)`,
            }}
          />
          <span id="totaltime">{formatDuration2(currentSong.dt)}</span>
        </div>
      </div>

      <div className="end">
        <div className="volume-control">
          <i
            className={
              volume === 0
                ? 'ri-volume-mute-line'
                : volume < 0.5
                  ? 'ri-volume-down-line'
                  : 'ri-volume-up-line'
            }
          ></i>
          <input
            type="range"
            min="0"
            max="100"
            value={volume * 100}
            onChange={handleVolumeChange}
            className="volume-bar"
            style={{
              background: `linear-gradient(to right, #4CAF50 ${volume * 100}%, #ddd ${volume * 100}%)`,
            }}
          />
        </div>
      </div>
    </div>
  );
};

export default MusicPlayer;
